//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import { LEARN_POLICY_EXTRA, LEARN_POLICY_NONE, LEARN_POLICY_OPTION, LEARN_POLICY_RECOMMEND, NodeInfo, update_node_data } from '@/api/roadmap_content';
import NodeWrap from './NodeWrap';
import { useRoadmapStores } from '../../store';
import { TOPIC_STATE_DOING, TOPIC_STATE_DONE, TOPIC_STATE_SKIP, TOPIC_STATE_TYPE } from '@/api/roadmap_state';
import { observer } from 'mobx-react';
import { get_content_text } from '@/components/Editor/utils';
import { BookTwoTone, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { request } from '@/utils/request';
import { Button, Input, message } from 'antd';



const TopicNode = (props: NodeProps<NodeInfo>) => {
    const roadmapStore = useRoadmapStores();

    const [rightTipText, setRightTipText] = useState<string | undefined>(undefined);
    const [userState, setUserState] = useState<TOPIC_STATE_TYPE | null>(null);

    const [quickEdit, setQuickEdit] = useState(false);
    const [title, setTitle] = useState("");

    const updateTitle = async () => {
        if (props.data.basic_info.node_data.TopicData == undefined) {
            return;
        }
        await request(update_node_data({
            session_id: roadmapStore.sessionId,
            roadmap_id: roadmapStore.roadmapId,
            node_id: props.data.node_id,
            node_data: {
                TopicData: {
                    ...props.data.basic_info.node_data.TopicData,
                    title: title,
                }
            },
        }));
        roadmapStore.onUpdateNode(props.data.node_id);
        setQuickEdit(false);
        message.info("修改成功");
    };

    const calcRightTipText = () => {
        const curStateInfo = roadmapStore.stateList.find(item => item.node_id == props.data.node_id);
        if (curStateInfo == undefined) {
            setRightTipText("未学习");
            setUserState(null);
            return;
        }
        const curState = curStateInfo.basic_info.state_data.TopicState?.state ?? TOPIC_STATE_DOING;
        setUserState(curState);
        if (curState == TOPIC_STATE_DOING) {
            setRightTipText("学习中");
        } else if (curState == TOPIC_STATE_DONE) {
            setRightTipText("已掌握");
        } else if (curState == TOPIC_STATE_SKIP) {
            setRightTipText("忽略");
        }
    };

    const getRightTipText2 = () => {
        if (roadmapStore.inEdit) {
            if (props.data.basic_info.node_data.TopicData?.content == "") {
                return undefined;
            }
            try {
                const content = get_content_text(props.data.basic_info.node_data.TopicData?.content ?? "");
                return `${content.length}字`;
            } catch (e) {
                const len = (props.data.basic_info.node_data.TopicData?.content ?? "").length;
                return `${len}字`;
            }
        } else {
            if (roadmapStore.adminUser) {
                return undefined;
            } else {
                const index = roadmapStore.noteList.findIndex(item => item.node_id == props.data.node_id);
                if (index == -1) {
                    return <BookTwoTone twoToneColor={["black", "#ccc"]} style={{ fontSize: "12px" }} />;
                } else {
                    return <BookTwoTone twoToneColor={["black", "orange"]} style={{ fontSize: "12px" }} />;
                }
            }
        }
    };

    const getBgColor = () => {
        if (roadmapStore.inEdit == false && userState != null && [TOPIC_STATE_DONE, TOPIC_STATE_SKIP].includes(userState)) {
            return "#ccc";
        }
        return props.data.basic_info.node_data.TopicData?.bg_color ?? "white";
    };

    const getLeftTipText = () => {
        if (props.data.basic_info.node_data.TopicData?.learn_policy == LEARN_POLICY_NONE) {
            return undefined;
        } else if (props.data.basic_info.node_data.TopicData?.learn_policy == LEARN_POLICY_RECOMMEND) {
            return "推荐学习";
        } else if (props.data.basic_info.node_data.TopicData?.learn_policy == LEARN_POLICY_OPTION) {
            return "可选学习";
        } else if (props.data.basic_info.node_data.TopicData?.learn_policy == LEARN_POLICY_EXTRA) {
            return "进阶学习";
        }
        return undefined;
    };

    const getLeftTipBgColor = () => {
        if (props.data.basic_info.node_data.TopicData?.learn_policy == LEARN_POLICY_NONE) {
            return undefined;
        } else if (props.data.basic_info.node_data.TopicData?.learn_policy == LEARN_POLICY_RECOMMEND) {
            return "purple";
        } else if (props.data.basic_info.node_data.TopicData?.learn_policy == LEARN_POLICY_OPTION) {
            return "green";
        } else if (props.data.basic_info.node_data.TopicData?.learn_policy == LEARN_POLICY_EXTRA) {
            return "grey";
        }
        return undefined;
    };

    useEffect(() => {
        if (roadmapStore.adminUser == false && roadmapStore.inEdit == false) {
            calcRightTipText();
        }
    }, [roadmapStore.stateList, roadmapStore.inEdit, roadmapStore.adminUser]);

    return (
        <NodeWrap hasHandle nodeData={props} style={{
            backgroundColor: getBgColor(),
            border: "2px solid black",
            borderRadius: "10px",
        }} leftTipText={getLeftTipText()} leftTipBgColor={getLeftTipBgColor()} rightTipText={rightTipText} rightTipText2={getRightTipText2()}>
            <div title={props.data.basic_info.node_data.TopicData?.title ?? ""}
                style={{
                    textOverflow: "ellipsis", overflow: quickEdit ? "visible" : "hidden", whiteSpace: "nowrap", padding: "4px 4px",
                    color: props.data.basic_info.node_data.TopicData?.font_color ?? "black",
                    fontWeight: props.data.basic_info.node_data.TopicData?.font_weight ?? 500,
                    fontSize: props.data.basic_info.node_data.TopicData?.font_size ?? 14,
                    textAlign: "center",
                    textDecoration: (roadmapStore.inEdit == false && userState != null && [TOPIC_STATE_DONE, TOPIC_STATE_SKIP].includes(userState)) ? "line-through" : undefined,
                }}
                onDoubleClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    if (roadmapStore.inEdit && quickEdit == false) {
                        setTitle(props.data.basic_info.node_data.TopicData?.title ?? "");
                        setQuickEdit(true);
                    }
                }}>
                {quickEdit == false &&
                    <>
                        {props.data.basic_info.node_data.TopicData?.title ?? ""}
                    </>
                }
                {quickEdit == true && (
                    <Input value={title} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setTitle(e.target.value);
                    }} prefix={<div>
                        <Button type="text" icon={<CloseOutlined />} style={{ minWidth: 0, padding: "0px 0px", color: "#777", zIndex: 9000 }} title='取消'
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setQuickEdit(false);
                            }} size='small'/>
                        <Button type="text" icon={<CheckOutlined />} style={{ minWidth: 0, padding: "0px 0px", color: "green", zIndex: 9000 }} title='保存'
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                updateTitle();
                            }} disabled={title.trim() == ""} size='small'/>
                    </div>} style={{ minWidth: 200, zIndex: 9000 }}
                        onKeyDown={e => {
                            if (e.key == "Enter") {
                                e.stopPropagation();
                                e.preventDefault();
                                updateTitle();
                            } else if (e.key == "Escape") {
                                e.stopPropagation();
                                e.preventDefault();
                                setQuickEdit(false);
                            }
                        }} autoFocus onBlur={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setQuickEdit(false);
                        }} />
                )}
            </div>
        </NodeWrap>
    );
};

export default observer(TopicNode);